package com.jiangyifen.robot.core.nlp;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.chatbot.model.v20171011.ChatRequest;
import com.aliyuncs.chatbot.model.v20171011.ChatResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.jiangyifen.robot.core.Robot;

public class AliyunNLPClient {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Robot robot;

	public SentimentResponse sentiment(String text) {
		SentimentResponse result = new SentimentResponse();
		try {

			IClientProfile profile = DefaultProfile.getProfile("cn-shanghai",
					robot.getRobotEntity().getAliyunAccessId(), robot.getRobotEntity().getAliyunAccessSecret());
			IAcsClient client = new DefaultAcsClient(profile);

			SentimentRequest t = new SentimentRequest();
			t.setText(text);

			CommonRequest request = new CommonRequest();
			request.setDomain("nlp.cn-shanghai.aliyuncs.com"); // 必须设置domain
			request.setUriPattern("/nlp/api/sentiment/ecommerce"); // 设置所要请求的API路径
			request.setMethod(MethodType.POST); // 设置请求方式，目前只支持POST
			request.setHttpContent(JSON.toJSONString(t).getBytes("utf-8"), "utf-8", FormatType.JSON); // 设置请求内容以及格式
			request.putHeadParameter("x-acs-signature-method", "HMAC-SHA1");
			request.putHeadParameter("x-acs-signature-nonce", UUID.randomUUID().toString()); // 设置请求唯一码，防止网络重放攻击

			logger.debug("sentimentRequest=" + JSON.toJSONString(request));
			CommonResponse response = client.getCommonResponse(request); // 请求并获取结果
			logger.debug("sentimentResponse=" + JSON.toJSONString(response));
			result = JSON.parseObject(response.getData(), SentimentResponse.class);
			logger.debug("result=" + JSON.toJSONString(result));
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return result;

	}

	private String textReplace(String input) {
		String output = input;
		try {
			// 把中文数字换成阿拉伯数字
			// TODO 这里需要替换的字符做成从数据库加载，并做一个相应的配置界面。
			// TODO 不同方言说数字的发音特点不同，会被ASR识别成不同的中文字。做成数据库+配置界面，方便实施者做调整
			output = input.replaceAll("一", "1").replaceAll("二", "2").replaceAll("两", "2").replaceAll("三", "3")
					.replaceAll("四", "4").replaceAll("伍", "5").replaceAll("陆", "6").replaceAll("柒", "7")
					.replaceAll("捌", "8").replaceAll("玖", "9").replaceAll("拾", "10");

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return output;
	}
	
	public ChatResponse chat(String sessionId, String text, String knowledgeId)
			throws ServerException, ClientException {
		DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", // 地域ID
				robot.getRobotEntity().getAliyunAccessId(), // RAM账号的AccessKey
															// ID
				robot.getRobotEntity().getAliyunAccessSecret()); // RAM账号AccessKey
																	// Secret

		IAcsClient client = new DefaultAcsClient(profile);

		ChatRequest chatRequest = new ChatRequest();
		chatRequest.setActionName("Chat");
		chatRequest.setInstanceId(robot.getRobotEntity().getXiaomiInstanceId());
		chatRequest.setSessionId(sessionId);
		chatRequest.setUtterance(textReplace(text));// 这里要对语音识别的返回做一些预处理，以便提高NLP的识别效果
		if (StringUtils.isNotBlank(knowledgeId)) {
			chatRequest.setKnowledgeId(knowledgeId);
		}
		logger.debug("chatRequest: " + JSON.toJSONString(chatRequest));

		ChatResponse chatResponse = client.getAcsResponse(chatRequest);
		logger.debug("chatResponse: " + JSON.toJSON(chatResponse));

		return chatResponse;

	}

	public Robot getRobot() {
		return robot;
	}

	public void setRobot(Robot robot) {
		this.robot = robot;
	}

}
